﻿
Imports System.IO
Imports System.Data
Imports System.Text.Encoding



Public Class Frm_Lopackinglist
    Implements IDServer.IDServer.IDServer
    Private WithEvents MainFrom As Frm_MainForm
    Private Elementrst As DataSet
    Private PackingRst As DataSet
    Private ElmentTable As DataTable
    Private IsLoadDate As Boolean
    Private PackingOperator As String
    Public Const EXCELCONNECTION As String = "Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties='Text; HDR=YES';"


    Public Property SelectObject() As Frm_MainForm
        Get
            Return MainFrom
        End Get
        Set(ByVal value As Frm_MainForm)
            MainFrom = value
        End Set
    End Property

#Region "Interface "
    Public Function ActionAdd() As Boolean Implements IDServer.IDServer.IDServer.ActionAdd
        Try
            If AddEnable = False Then
                MessageBox.Show("對不起，您沒有新增權限", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                Exit Function
            End If


            Me.TabControl1.SelectedIndex = 1
            Me.TabControl2.SelectedIndex = 1
            Me.BtnSave.Enabled = True

            Dim B As Boolean = True
            EnableControl(B)
            ClearControl()

            Me.TxtPackingDate.Text = ServerDate

            With MainFrom
                .ToolStripAdd.Enabled = False
                .ToolStripEdit.Enabled = False
                .ToolStripDelete.Enabled = False
                .ToolStripSave.Enabled = True
                .ToolStripCancel.Enabled = True
            End With
        Catch ex As Exception
            MessageBox.Show("Error : ActionAdd()" + ex.ToString, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Function

    Public Function ActionCancel() As Boolean Implements IDServer.IDServer.IDServer.ActionCancel
        Try
            With MainFrom
                .ToolStripSave.Enabled = False
                .ToolStripAdd.Enabled = True
                .ToolStripEdit.Enabled = False
                .ToolStripCancel.Enabled = False
                .ToolStripDelete.Enabled = False
            End With


            Dim B As Boolean = False
            EnableControl(B)
        Catch ex As Exception
            MessageBox.Show("Error : ActionCancel()" + ex.ToString, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Function

    Public Function ActionDelete() As Boolean Implements IDServer.IDServer.IDServer.ActionDelete

    End Function

    Public Function ActionEdit() As Boolean Implements IDServer.IDServer.IDServer.ActionEdit
        Try
            If EditEnable = False Then
                MessageBox.Show("對不起，您沒有修改權限", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                Exit Function
            End If

            'If PackingOperator.ToLower <> PubUserName.ToString Then
            '    MessageBox.Show("此單非您所創建！不能修改", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
            '    Exit Function
            'End If

            With MainFrom
                .ToolStripAdd.Enabled = False
                .ToolStripEdit.Enabled = False
                .ToolStripSave.Enabled = True
                .ToolStripDelete.Enabled = False
                .ToolStripCancel.Enabled = True
            End With

            '清空數據，防止元件重複
            Dim Newtable As DataTable = CType(Me.DGVElement.DataSource, DataTable)
            Newtable.Clear()
            Me.DGVElement.DataSource = Newtable


            Dim B As Boolean = True
            EnableControl(B)
        Catch ex As Exception
            MessageBox.Show("Error : ActionEdit()" + ex.ToString, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Function

    Public Function ActionExport() As Boolean Implements IDServer.IDServer.IDServer.ActionExport

    End Function

    Public Function ActionFilter() As Boolean Implements IDServer.IDServer.IDServer.ActionFilter

    End Function

    Public Function ActionGoFirst() As Boolean Implements IDServer.IDServer.IDServer.ActionGoFirst

    End Function

    Public Function ActionGoLast() As Boolean Implements IDServer.IDServer.IDServer.ActionGoLast

    End Function

    Public Function ActionGoNext() As Boolean Implements IDServer.IDServer.IDServer.ActionGoNext

    End Function

    Public Function ActionGoPrevious() As Boolean Implements IDServer.IDServer.IDServer.ActionGoPrevious

    End Function

    Public Function ActionImport() As Boolean Implements IDServer.IDServer.IDServer.ActionImport

    End Function

    Public Function ActionInitialize() As Boolean Implements IDServer.IDServer.IDServer.ActionInitialize

    End Function

    Public Function ActionPrint() As Boolean Implements IDServer.IDServer.IDServer.ActionPrint
        Try
            Dim mPackingBillNum As String
            Dim mDs As DataSet
            Dim Pathstr As String = ""
            Dim sql As String = ""
            Dim ConfigNode() As String = ReadConfigFile.Split(";")
            Dim mServer As String = ""
            Dim mDataBase As String = ""
            Dim mUserID As String = ""
            Dim mPassword As String = ""

            'If Me.DGVMasterQ.SelectedRows.Count > 0 Then
            '    For i As Integer = 0 To Me.DGVMasterQ.SelectedRows.Count - 1
            '        BoNum += "''" & Me.DGVMasterQ.SelectedRows(i).Cells("BoNum").Value & "'',"
            '    Next
            '    BoNum = BoNum.Remove(BoNum.Length - 1, 1)
            'End If
            If Me.DGVMasterQ.Rows.Count > 0 Then
                If Not Me.DGVMasterQ.CurrentRow Is Nothing Then
                    mPackingBillNum = Me.DGVMasterQ.CurrentRow.Cells("fPackingBillNum").Value
                End If
            Else
                MessageBox.Show("沒有數據列印", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
                Exit Function
            End If

            Pathstr = GetReportPath("LO", "LO_Packing.rpt")
            For i As Integer = 0 To ConfigNode.Length - 1
                If ConfigNode(i).Split("=")(0).ToLower = "Server".ToLower Then
                    mServer = ConfigNode(i).Split("=")(1)
                End If
                If ConfigNode(i).Split("=")(0).ToLower = "DataBase".ToLower Then
                    mDataBase = ConfigNode(i).Split("=")(1)
                End If
                If ConfigNode(i).Split("=")(0).ToLower = "Uid".ToLower Then
                    mUserID = ConfigNode(i).Split("=")(1)
                End If
                If ConfigNode(i).Split("=")(0).ToLower = "Pwd".ToLower Then
                    mPassword = ConfigNode(i).Split("=")(1)
                End If
            Next

            Dim myReportDoc As New CrystalDecisions.CrystalReports.Engine.ReportDocument
            Dim myParameterValues As New CrystalDecisions.Shared.ParameterValues
            Dim myDiscreteValue As New CrystalDecisions.Shared.ParameterDiscreteValue

            Dim logonInfo As New CrystalDecisions.Shared.TableLogOnInfo
            Dim table As CrystalDecisions.CrystalReports.Engine.Table
            myReportDoc.Load(Pathstr)

            For Each table In myReportDoc.Database.Tables
                logonInfo = table.LogOnInfo
                With logonInfo.ConnectionInfo
                    .ServerName = mServer
                    .DatabaseName = mDataBase
                    .UserID = mUserID
                    .Password = mPassword
                End With
                table.ApplyLogOnInfo(logonInfo)
            Next
            sql += "Exec PackingList '" & mPackingBillNum & "';"
            mDs = New DataSet
            mDs = ReturnDataset(sql)

            myReportDoc.SetDataSource(mDs.Tables(0))

            My.Forms.Frm_Report.CrystalReportViewer1.ReportSource = myReportDoc
            My.Forms.Frm_Report.CrystalReportViewer1.Zoom(1)
            My.Forms.Frm_Report.CrystalReportViewer1.DisplayGroupTree = False
            Frm_Report.ShowDialog()
        Catch ex As Exception
            MessageBox.Show("Error:ActionPrint！", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
        End Try
    End Function

    Public Function ActionSave() As Boolean Implements IDServer.IDServer.IDServer.ActionSave
        Try
            Dim Sql As String = ""

            Dim fPackingBillNum As String = ReadPackingBill()
            Dim fBoxNum As String = Me.TxtBoxNum.Text
            Dim fPackingDate As String = Me.TxtPackingDate.Text
            Dim fBoNum As String = Me.TxtOutStoreBillNum.Text
            Dim fRemark As String = Me.TxtRemark.Text
            Dim fOperator As String = PubUserCode
            Dim fOperateComputer As String = My.Computer.Name

            If Me.TxtBoxNum.Text = "" Then
                MessageBox.Show("箱號不能為空！", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
            End If
            If Me.TxtPackingDate.Text = "" Then
                MessageBox.Show("包裝日期不能為空！", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
            End If

            If IsExist(Me.TxtPackingBillNum.Text.ToString) = True Then
                Sql = "update LO_PackingMaster set fBoxNum='" & fBoxNum & "',fPackingDate='" & fPackingDate & "',fBoNum ='" & fBoNum & "', fRemark='" & fRemark & "', fOperateComputer='" & fOperateComputer & "' where fPackingBillNum='" & Me.TxtPackingBillNum.Text.ToString & "'"
                ReturnObject(Sql)
                MessageBox.Show("修改成功！", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
            Else
                Sql = "insert into LO_PackingMaster (fPackingBillNum, fBoxNum, fPackingDate, fBoNum, fRemark, fOperator, fOperateComputer, fCheckMan, fCheckDate, fCheckComputer, fStatus)"
                Sql &= "values ('" & fPackingBillNum & "','" & fBoxNum & "','" & fPackingDate & "','" & fBoNum & "','" & fRemark & "','" & fOperator & "','" & fOperateComputer & "','','','','A')"

                ReturnObject(Sql)
                MessageBox.Show("保存成功！", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                Me.TxtPackingBillNum.Text = fPackingBillNum
            End If

            With MainFrom
                .ToolStripSave.Enabled = False
                .ToolStripCancel.Enabled = False
                .ToolStripAdd.Enabled = True
                .ToolStripEdit.Enabled = True
            End With
            Me.TabControl2.SelectedIndex = 0
            Dim NewTable As DataTable = CType(Me.DGVMaster.DataSource, DataTable)
            NewTable.Clear()
            Dim NewRow As DataRow = NewTable.NewRow
            NewRow("fPackingBillNum") = Me.TxtPackingBillNum.Text
            NewRow("fBoxNum") = Me.TxtBoxNum.Text
            NewRow("fPackingDate") = Me.TxtPackingDate.Text
            NewRow("fBoNum") = Me.TxtOutStoreBillNum.Text
            NewRow("fRemark") = Me.TxtRemark.Text
            NewRow("fOperator") = PubUserCode
            NewRow("fOperateComputer") = My.Computer.Name
            NewRow("fCheckMan") = ""
            NewRow("fCheckDate") = ""
            NewRow("fCheckComputer") = ""
            NewRow("fStatus") = "A"
            NewTable.Rows.Add(NewRow)
            NewTable.AcceptChanges()
            Me.DGVMaster.DataSource = NewTable

            Dim B As Boolean = False
            EnableControl(B)

        Catch ex As Exception
            MessageBox.Show("Error:ActionSave！", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
        End Try
    End Function

    Public Function ActionSelect() As Boolean Implements IDServer.IDServer.IDServer.ActionSelect

    End Function
#End Region

#Region "Function and Sub"

    Private Function IsExist(ByVal fPackingBillNum As String) As Boolean
        Try
            Dim Rst As DataSet
            Dim Sql As String = "select * from LO_PackingMaster where fPackingBillNum='" & fPackingBillNum & "' "
            Rst = New DataSet
            Rst = ReturnDataset(Sql)
            If Rst.Tables(0).Rows.Count > 0 Then
                Return True
            Else
                Return False
            End If
        Catch ex As Exception
            MessageBox.Show("Error:ReadPackingBill！", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
        End Try
    End Function

    Private Function ReadPackingBill() As String
        Try
            Dim sql As String
            Dim fHead As String = "p" + PubCompanyCode
            Dim fPackingBillNum As String = String.Empty
            sql = "exec ReturnBillNum 'LO_PackingMaster','fPackingBillNum','" & fHead & "'"
            fPackingBillNum = GetValue(sql)
            Return fPackingBillNum
        Catch ex As Exception
            MessageBox.Show("Error:ReadPackingBill！", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
        End Try
    End Function

    Private Sub EnableControl(ByVal B As Boolean)
        Try
            Me.TxtBoxNum.Enabled = B
            Me.TxtPackingDate.Enabled = B
            Me.TxtOutStoreBillNum.Enabled = B
            Me.TxtRemark.Enabled = B
            Me.BtnSave.Enabled = B
            'Me.TabControl2.Enabled = B
        Catch ex As Exception
            MessageBox.Show("Error : EnableControl" + ex.ToString, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    Private Sub ClearControl()
        Try
            Me.TxtPackingBillNum.Text = ""
            Me.TxtBoxNum.Text = ""
            Me.TxtPackingDate.Text = ""
            Me.TxtOutStoreBillNum.Text = ""
            Me.TxtRemark.Text = ""
        Catch ex As Exception
            MessageBox.Show("Error : ClearControl" + ex.ToString, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub
#End Region

#Region "BindHast"

    Public Function BindHast(ByVal index As Integer) As Hashtable
        Try
            Dim mHastTable As New Hashtable
            With mHastTable
                Select Case index
                    Case 0
                        'fPackingBillNum, fBoxNum, fPackingDate, fBoNum, fRemark, fOperator, fOperateComputer, fCheckMan, fCheckDate, fCheckComputer, fStatus
                        .Add("fPackingBillNum", "包裝單號")
                        .Add("fBoxNum", "箱號")
                        .Add("fPackingDate", "包裝日期")
                        .Add("fBoNum", "出貨單號")
                        .Add("fRemark", "備注")
                        .Add("fOperator", "操作人")
                        .Add("fOperateComputer", "操作電腦")
                        .Add("fCheckMan", "審核人")
                        .Add("fCheckDate", "審核日期")
                        .Add("fCheckComputer", "審核電腦")
                        .Add("fStatus", "狀態")
                    Case 1
                        'fPackingBillNum, fBoNum, fBarcode, fSupplierItem, fGoodName, fGoodsAmount, fBatchaNo, fStorPlace, fGoodsOthers
                        '.Add("fPackingBillNum", "包裝單號")
                        .Add("fBoNum", "出貨單號")
                        .Add("fBarcode", "條碼")
                        .Add("fSupplierItem", "供應商編號")
                        .Add("fGoodName", "貨品名稱")
                        .Add("fGoodsAmount", "貨品數量")
                        .Add("fBatchaNo", "批次")
                        .Add("fStorPlace", "庫位")
                        .Add("fGoodsOthers", "其他說明")
                    Case 2
                        'fPackingBillNum, fBarcode, fEnname, fSupplierItem, fElement, fElementAmount, fElementUnit, fElementBatch, fElementPlace, fElementStatus
                        '.Add("fPackingBillNum", "包裝單號")
                        .Add("fBoNum", "出貨單號")
                        .Add("fBarcode", "貨品條碼")
                        .Add("fEnname", "英文名稱")
                        .Add("fSupplierItem", "供應商編號")
                        .Add("fElement", "元件")
                        .Add("fElementAmount", "元件數量")
                        .Add("fElementUnit", "元件單位")
                        .Add("fElementBatch", "元件批次")
                        .Add("fElementPlace", "元件庫位")
                        .Add("fElementStatus", "元件狀態")
                    Case 3
                        .Add("BoNumB", "出貨單號")
                        .Add("GoodsBarcode", "貨品條碼")
                        .Add("Enname", "英文名稱")
                        .Add("supperitem", "供應商編號")
                        .Add("Element", "元件")
                        .Add("ElementAmount", "元件數量")
                        .Add("ElementUnit", "元件單位")
                        .Add("ElementBatch", "元件批次")
                        .Add("ElementPlace", "元件庫位")
                        .Add("ElementStatus", "元件狀態")


                End Select
            End With
            Return mHastTable
        Catch ex As Exception
            MessageBox.Show("Error : ActionAdd()" + ex.ToString, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Function

    Public Sub BindElement()
        Try
            ElmentTable = New DataTable
            With ElmentTable.Columns
                '.Add("fPackingBillNum")
                .Add("fBoNum")
                .Add("fBarcode")
                .Add("fEnname")
                .Add("fSupplierItem")
                .Add("fElement")
                .Add("fElementAmount")
                .Add("fElementUnit")
                .Add("fElementBatch")
                .Add("fElementPlace")
                .Add("fElementStatus")
            End With
            Me.DGVElement.DataSource = ElmentTable

            With Me.DGVElement
                For i As Integer = 0 To .Columns.Count - 1
                    Dim mKey As String = .Columns(i).Name
                    Dim CaptionStr As String = BindHast(2).Item(mKey)
                    .Columns(i).HeaderText = CaptionStr
                Next
            End With

        Catch ex As Exception
            MessageBox.Show("Error : BindElement()" + ex.ToString, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    Public Sub BindLoadElement()
        Try
            Dim mtable As DataTable = New DataTable
            With mtable.Columns
                ' .Add("fPackingBillNum")
                .Add("BoNumB")
                .Add("GoodsBarcode")
                .Add("Enname")
                .Add("supperitem")
                .Add("Element")
                .Add("ElementAmount")
                .Add("ElementUnit")
                .Add("ElementBatch")
                .Add("ElementPlace")
                .Add("ElementStatus")
            End With
            Me.DGVLoadElement.DataSource = mtable

            With Me.DGVLoadElement
                For i As Integer = 0 To .Columns.Count - 1
                    Dim mKey As String = .Columns(i).Name
                    Dim CaptionStr As String = BindHast(3).Item(mKey)
                    .Columns(i).HeaderText = CaptionStr
                Next
            End With

        Catch ex As Exception
            MessageBox.Show("Error : BindLoadElement()" + ex.ToString, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    'Public Sub BindDGVDetail()
    '    Try
    '        Dim mtable As DataTable = New DataTable
    '        With mtable.Columns
    '            '.Add("fPackingBillNum")
    '            .Add("fBoNum")
    '            .Add("fBarcode")
    '            .Add("fSupplierItem")
    '            .Add("fGoodName")
    '            .Add("fGoodsAmount")
    '            .Add("fBatchaNo")
    '            .Add("fStorPlace")
    '            .Add("fGoodsOthers")
    '        End With
    '        Me.DGVDetail.DataSource = mtable

    '        With Me.DGVDetail
    '            For i As Integer = 0 To .Columns.Count - 1
    '                Dim mKey As String = .Columns(i).Name
    '                Dim CaptionStr As String = BindHast(1).Item(mKey)
    '                .Columns(i).HeaderText = CaptionStr
    '            Next
    '        End With

    '    Catch ex As Exception
    '        MessageBox.Show("Error : BindDGVMaster()" + ex.ToString, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
    '    End Try
    'End Sub
    Public Sub BindDGVMasterQ()
        Try
            Dim mtable As DataTable = New DataTable
            With mtable.Columns
                .Add("fPackingBillNum")
                .Add("fBoxNum")
                .Add("fPackingDate")
                .Add("fBoNum")
                .Add("fRemark")
                .Add("fOperator")
                .Add("fOperateComputer")
                .Add("fCheckMan")
                .Add("fCheckDate")
                .Add("fCheckComputer")
                .Add("fStatus")
            End With
            Me.DGVMasterQ.DataSource = mtable

            With Me.DGVMasterQ
                For i As Integer = 0 To .Columns.Count - 1
                    Dim mKey As String = .Columns(i).Name
                    Dim CaptionStr As String = BindHast(0).Item(mKey)
                    .Columns(i).HeaderText = CaptionStr
                Next
            End With

        Catch ex As Exception
            MessageBox.Show("Error : BindDGVMasterQ()" + ex.ToString, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    Public Sub BindDGVMaster()
        Try
            Dim mtable As DataTable = New DataTable
            With mtable.Columns
                .Add("fPackingBillNum")
                .Add("fBoxNum")
                .Add("fPackingDate")
                .Add("fBoNum")
                .Add("fRemark")
                .Add("fOperator")
                .Add("fOperateComputer")
                .Add("fCheckMan")
                .Add("fCheckDate")
                .Add("fCheckComputer")
                .Add("fStatus")
            End With
            Me.DGVMaster.DataSource = mtable

            With Me.DGVMaster
                For i As Integer = 0 To .Columns.Count - 1
                    Dim mKey As String = .Columns(i).Name
                    Dim CaptionStr As String = BindHast(0).Item(mKey)
                    .Columns(i).HeaderText = CaptionStr
                Next
            End With

        Catch ex As Exception
            MessageBox.Show("Error : BindDGVMaster()" + ex.ToString, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub
#End Region

#Region "Windows Events"
    Private Sub Frm_Lopackinglist_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Try
            Dim B As Boolean = False
            EnableControl(B)

            BindDGVMasterQ()
            BindDGVMaster()
            'BindDGVDetail()
            BindElement()
            BindLoadElement()
            LoadComb()

            'Me.ChkboxIsOut.Checked = True
            'Me.ChkboxNotIsOut.Checked = False

        Catch ex As Exception
            MessageBox.Show("Error : Frm_Lopackinglist_Load" + ex.ToString, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub
#End Region

    Private Sub LoadComb()
        Try
            Dim sql As String = ""
            Dim rst As New DataSet

            sql = "select * from Sys_UserManage"
            rst = ReturnDataset(sql)
            With Me.CmbOperatorQ
                .DataSource = rst.Tables(0)
                .DisplayMember = "username"
                .ValueMember = "usercode"
                .Text = ""
            End With

            With Me.CmbCheckMan
                .DataSource = rst.Tables(0)
                .DisplayMember = "username"
                .ValueMember = "usercode"
                .Text = ""
            End With
        Catch ex As Exception
            MessageBox.Show("Error : LoadComb" + ex.ToString, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    Private Sub BtnFind_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnFind.Click
        Try

            Dim sql As String = "select * from LO_PackingMaster where 1=1 "
            Dim ElementSql As String = "select a.fPackingBillNum,a.fBoxNum,a.FBoNum,a.fPackingDate,a.fOperateComputer,a.fCheckMan,b.* from  LO_PackingMaster a inner join LO_PackingElement b on a.fPackingBillNum=b.fPackingBillNum where 1=1 "
            If Me.TxtPackingBillNumQ.Text.Length > 0 Then
                sql &= " and fPackingBillNum='" & Me.TxtPackingBillNumQ.Text.ToString.Trim & "'"
                ElementSql &= " and a.fPackingBillNum='" & Me.TxtPackingBillNumQ.Text.ToString.Trim & "'"

            End If

            If Me.TxtPackingDateQ.Text.Length > 0 Then
                sql &= " and fPackingDate='" & Me.TxtPackingDateQ.Text.ToString.Trim & "' "
                ElementSql &= " and a.fPackingDate='" & Me.TxtPackingDateQ.Text.ToString.Trim & "' "

            End If

            If Me.CmbOperatorQ.Text.Length > 0 Then
                sql &= " and fOperator='" & Me.CmbOperatorQ.SelectedValue & "'"
                ElementSql &= " and a.fOperator='" & Me.CmbOperatorQ.SelectedValue & "'"

            End If

            If Me.CmbCheckMan.Text.Length > 0 Then
                sql &= " and fCheckMan='" & Me.CmbCheckMan.SelectedValue & "' "
                ElementSql &= " and a.fCheckMan='" & Me.CmbCheckMan.SelectedValue & "' "

            End If

            If Me.TxtOutStoreBillNumQ.Text.Length > 0 Then
                sql &= " and fBoNum like '%" & Me.TxtOutStoreBillNumQ.Text & "%' "
                ElementSql &= " and a.fBoNum like '%" & Me.TxtOutStoreBillNumQ.Text & "%' "
            End If

            sql &= ElementSql

            PackingRst = ReturnDataset(sql)
            Me.DGVMasterQ.DataSource = PackingRst.Tables(0)
            'Me.DGVElement.DataSource = PackingRst.Tables(1)

            If Me.DGVMasterQ.Rows.Count > 0 Then
                MainFrom.ToolStripDelete.Enabled = True
                MainFrom.ToolStripPrint.Enabled = True
            End If

        Catch ex As Exception
            MessageBox.Show("Error : BtnFind_Click" + ex.ToString, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    Private Sub BtnLoadElement_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnLoadElement.Click
        Try
            Me.CheckBox3.Checked = True

            Dim sql As String = ""
            sql = "select a.BoNumB, a.GoodsBarcode, a.Element, a.Elementamount, a.ElementBatch,a.ElementPlace, a.ElementStatus, a.ElementUnit,b.enname,b.supperitem from stor_elementout a left join bsc_goods b on a.goodsbarcode =b.barcode where 1=1"
            If Me.CheckBox1.Checked = True Then
                sql &= " and BonumB='" & Me.TxtLoadBoNum.Text.ToString & "'"
            End If
            If Me.CheckBox2.Checked = True Then
                sql &= " and isnull(BoNumB,'') in (select isnull(bonum,'') from Stor_TradeMaster where DeliverDate between '" & FormatDate(Me.DtpLoadFrom.Value) & "' and '" & FormatDate(Me.DtpLoadTo.Value) & "')"
            End If
            If Me.CheckBox3.Checked = True Then
                sql &= " and isnull(Element,'') not in (select isnull(felement,'') from  dbo.LO_PackingElement) "
            End If
            Elementrst = New DataSet
            Elementrst = ReturnDataset(sql)
            Me.DGVLoadElement.DataSource = Elementrst.Tables(0)

            Dim NewTable As DataTable = CType(Me.DGVElement.DataSource, DataTable)
            NewTable.Clear()
            Me.DGVElement.DataSource = NewTable

            DataGridViewSortModeEnabled(Me.DGVLoadElement)

            IsLoadDate = True
        Catch ex As Exception
            MessageBox.Show("Error : BtnLoadElement_Click" + ex.ToString, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try

        ''Frm_Lopackinglist
    End Sub

    Private Sub BtnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnSave.Click
        Try
            If Me.TxtPackingBillNum.Text = "" Then
                MessageBox.Show("包裝單為空，請設置包裝單！", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                Exit Sub
            End If
            Dim fPackingBillNum As String = Me.TxtPackingBillNum.Text.ToString
            If Me.DGVElement.Rows.Count < 1 Then
                MessageBox.Show("沒有元件可以保存！", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                Exit Sub
            End If

            Dim sql As String = ""
            Dim Sqlconn As New SqlClient.SqlConnection
            Dim Sqlcmd As New SqlClient.SqlCommand
            Dim SqlBulk As SqlClient.SqlBulkCopy

            Sqlconn = GetConn()
            If Sqlconn.State = ConnectionState.Closed Then
                Sqlconn.Open()
            End If
            Dim TransSQL As SqlClient.SqlTransaction = Sqlconn.BeginTransaction
            SqlBulk = New SqlClient.SqlBulkCopy(Sqlconn, SqlClient.SqlBulkCopyOptions.Default, TransSQL)
            Dim Newtable As DataTable = ReturnTable(fPackingBillNum, 0)
            SqlBulk.DestinationTableName = "LO_PackingElement"
            SqlBulk.BulkCopyTimeout = 100
            SqlBulk.WriteToServer(Newtable)

            MsgBox("保存成功，謝謝！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
            TransSQL.Commit()

            Me.BtnSave.Enabled = False
            With MainFrom
                .ToolStripSave.Enabled = False
                .ToolStripCancel.Enabled = False
                .ToolStripEdit.Enabled = True
                .ToolStripAdd.Enabled = True
            End With


            '清空DGVElement 的記錄
            Dim Mtable As DataTable = CType(Me.DGVElement.DataSource, DataTable)
            Mtable.Clear()
            Me.DGVElement.DataSource = Mtable

        Catch ex As Exception
            MessageBox.Show("Error : BtnSave_Click()" + ex.ToString, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    Private Function IsArranged(ByVal Element As String) As Boolean
        Try
            Dim NewTable As DataTable = CType(Me.DGVElement.DataSource, DataTable)
            Dim Newrows() As DataRow = NewTable.Select("felement='" & Element & "'")
            If Newrows.Length > 0 Then
                Return True
            Else
                Return False
            End If
        Catch ex As Exception
            MessageBox.Show("Error : IsArranged" + ex.ToString, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try

    End Function

    Private Function ReturnTable(ByVal fPackingBillNum As String, ByVal index As Integer) As DataTable
        Try
            Dim mtable As DataTable = New DataTable
            With mtable.Columns
                Select Case index
                    Case 0
                        'fPackingBillNum, fBoxNum, fBarcode, fEnname, fSupplierItem, fElement, fElementAmount, fElementUnit, fElementBatch, fElementPlace, fElementStatus
                        .Add("fPackingBillNum")
                        .Add("fBoxNum")
                        .Add("fBoNum")
                        .Add("fBarcode")
                        .Add("fEnname")
                        .Add("fSupplierItem")
                        .Add("fElement")
                        .Add("fElementAmount")
                        .Add("fElementUnit")
                        .Add("fElementBatch")
                        .Add("fElementPlace")
                        .Add("fElementStatus")
                End Select

                If Me.DGVElement.Rows.Count > 0 Then
                    For i As Integer = 0 To Me.DGVElement.Rows.Count - 1
                    Next
                    For i As Integer = 0 To Me.DGVElement.Rows.Count - 1
                        If Me.DGVElement.Rows(i).IsNewRow = False Then
                            Dim NewRow As DataRow = mtable.NewRow
                            NewRow("fPackingBillNum") = fPackingBillNum
                            NewRow("fBoxNum") = Me.TxtBoxNum.Text
                            NewRow("fBoNum") = Me.DGVElement.Rows(i).Cells("fBoNum").Value
                            NewRow("fBarcode") = Me.DGVElement.Rows(i).Cells("fBarcode").Value
                            NewRow("fEnname") = Me.DGVElement.Rows(i).Cells("fEnname").Value
                            NewRow("fSupplierItem") = Me.DGVElement.Rows(i).Cells("fSupplierItem").Value
                            NewRow("fElement") = Me.DGVElement.Rows(i).Cells("fElement").Value
                            NewRow("fElementAmount") = Me.DGVElement.Rows(i).Cells("fElementAmount").Value
                            NewRow("fElementUnit") = Me.DGVElement.Rows(i).Cells("fElementUnit").Value
                            NewRow("fElementBatch") = Me.DGVElement.Rows(i).Cells("fElementBatch").Value
                            NewRow("fElementPlace") = Me.DGVElement.Rows(i).Cells("fElementPlace").Value
                            NewRow("fElementStatus") = Me.DGVElement.Rows(i).Cells("fElementStatus").Value
                            mtable.Rows.Add(NewRow)
                        End If
                    Next
                    mtable.AcceptChanges()
                End If
                Return mtable
            End With
        Catch ex As Exception

        End Try
    End Function

    Private Sub txtElement_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtElement.KeyDown
        Try

            Lab_Info.Text = ""

            If IsLoadDate = False Then
                Lab_Info.Text = "查詢數據，不能掃描，請先加載！"
                Me.txtElement.Text = ""
                Me.txtElement.Focus()
                Exit Sub
            End If
            If Me.TxtPackingBillNum.Text = "" Then
                Lab_Info.Text = "包裝單為空，請設置包裝單！"
                Me.txtElement.Text = ""
                Me.txtElement.Focus()
                Exit Sub
            End If
            If IsArranged(Me.txtElement.Text.ToString) = True Then
                Lab_Info.Text = "元件已經掃描！"
                'If MessageBox.Show("元件已經掃描！", "確認一下！", MessageBoxButtons.OKCancel, MessageBoxIcon.Information) = DialogResult.OK Then
                Me.txtElement.Text = ""
                Me.txtElement.Focus()
                Exit Sub
                'End If
            End If

            If e.KeyCode = Keys.Enter Then
                Dim fElemnt As String = Me.txtElement.Text
                Dim ElementTable As DataTable = Elementrst.Tables(0)
                Dim Rows() As DataRow = ElementTable.Select("element='" & fElemnt & "'")
                If Rows.Length > 0 Then
                    For Each row As DataRow In Rows
                        Dim mTable As DataTable = CType(Me.DGVElement.DataSource, DataTable)
                        Dim NewRow As DataRow = mTable.NewRow
                        NewRow("fBoNum") = row("BoNumB")
                        NewRow("fBarcode") = row("GoodsBarcode")
                        NewRow("fEnname") = row("Enname")
                        NewRow("fSupplierItem") = row("supperitem")
                        NewRow("fElement") = row("Element")
                        NewRow("fElementAmount") = row("ElementAmount")
                        NewRow("fElementUnit") = row("ElementUnit")
                        NewRow("fElementBatch") = row("ElementBatch")
                        NewRow("fElementPlace") = row("ElementPlace")
                        NewRow("fElementStatus") = row("ElementStatus")
                        mTable.Rows.Add(NewRow)
                        mTable.AcceptChanges()
                        Me.DGVElement.DataSource = mTable
                        Me.DGVLoadElement.CurrentRow.Selected = True
                        Me.DGVLoadElement.CurrentRow.DefaultCellStyle.BackColor = Color.Blue

                        '刪除內存數據
                        ElementTable.Rows.Remove(row)
                        ElementTable.AcceptChanges()
                    Next
                End If
                Me.txtElement.Text = ""
                Me.txtElement.Focus()
            End If
        Catch ex As Exception

        End Try
    End Sub

    Private Sub BtnLoadElementQ_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnLoadElementQ.Click

        Try
            Dim sql As String = ""
            sql = "select a.BoNumB, a.GoodsBarcode, a.Element, a.Elementamount, a.ElementBatch,a.ElementPlace, a.ElementStatus, a.ElementUnit,b.enname,b.supperitem from stor_elementout a left join bsc_goods b on a.goodsbarcode =b.barcode where 1=1"
            If Me.CheckBox1.Checked = True Then
                sql &= " and isnull(BonumB,'')='" & Me.TxtLoadBoNum.Text.ToString & "'"
            End If
            If Me.CheckBox2.Checked = True Then
                sql &= " and isnull(BoNumB,'') in (select isnull(bonum,'') from Stor_TradeMaster where DeliverDate between '" & FormatDate(Me.DtpLoadFrom.Value) & "' and '" & FormatDate(Me.DtpLoadTo.Value) & "')"
            End If
            If Me.CheckBox3.Checked = True Then
                sql &= " and  not exists  (select isnull(felement,'') as felement  from  dbo.LO_PackingElement c where a.element=c.felement) "
            End If
            Elementrst = New DataSet
            Elementrst = ReturnDataset(sql)
            Me.DGVLoadElement.DataSource = Elementrst.Tables(0)


            IsLoadDate = False
        Catch ex As Exception
            MessageBox.Show("Error : BtnLoadElement_Click" + ex.ToString, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    Private Sub DGVMasterQ_CellClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DGVMasterQ.CellClick
    End Sub

    Private Sub DGVMasterQ_CellDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DGVMasterQ.CellDoubleClick
        Try
            If Me.DGVMasterQ.Rows.Count > 0 Then
                Dim fPackingBillNum As String = Me.DGVMasterQ.CurrentRow.Cells("fPackingBillNum").Value
                PackingOperator = Me.DGVMasterQ.CurrentRow.Cells("fOperator").Value
                Dim kk As DataTable = CType(Me.DGVMasterQ.DataSource, DataTable)
                Dim NewRow() As DataRow = kk.Select("fPackingBillNum='" & fPackingBillNum & "'")
                Dim Rows() As DataRow = PackingRst.Tables(1).Select("fPackingBillNum='" & fPackingBillNum & "'")

                Dim Tb As DataTable = CType(Me.DGVMaster.DataSource, DataTable)
                'Dim mTable As DataTable = CType(Me.DGVElement.DataSource, DataTable)
                Tb.Clear()
                ElmentTable.Clear()

                If NewRow.Length > 0 Then
                    For Each row As DataRow In NewRow
                        Dim Rw As DataRow = Tb.NewRow
                        Me.TxtPackingBillNum.Text = row("fPackingBillNum")
                        Me.TxtBoxNum.Text = row("fBoxNum")
                        Me.TxtPackingDate.Text = row("fPackingDate")
                        Me.TxtOutStoreBillNum.Text = row("fBoNum")
                        Me.TxtRemark.Text = row("fRemark")

                        Rw("fPackingBillNum") = row("fPackingBillNum")
                        Rw("fBoxNum") = row("fBoxNum")
                        Rw("fPackingDate") = row("fPackingDate")
                        Rw("fBoNum") = row("fBoNum")
                        Rw("fRemark") = row("fRemark")

                        Rw("fOperator") = row("fOperator")
                        Rw("fOperateComputer") = row("fOperateComputer")
                        Rw("fCheckMan") = row("fCheckMan")
                        Rw("fCheckDate") = row("fCheckDate")
                        Rw("fCheckComputer") = row("fCheckComputer")
                        Rw("fStatus") = row("fStatus")

                        Tb.Rows.Add(Rw)
                        Tb.AcceptChanges()
                        Me.DGVMaster.DataSource = Tb
                        Me.TabControl1.SelectedIndex = 1
                        Me.TabControl2.SelectedIndex = 0

                        MainFrom.ToolStripEdit.Enabled = True
                    Next
                End If
                If Rows.Length > 0 Then
                    For Each Elementrow As DataRow In Rows
                        Dim row As DataRow = ElmentTable.NewRow
                        row("fBoNum") = Elementrow("fBoNum")
                        row("fBarcode") = Elementrow("fBarcode")
                        row("fEnname") = Elementrow("fEnname")
                        row("fSupplierItem") = Elementrow("fSupplierItem")
                        row("fElement") = Elementrow("fElement")
                        row("fElementAmount") = Elementrow("fElementAmount")
                        row("fElementUnit") = Elementrow("fElementUnit")
                        row("fElementBatch") = Elementrow("fElementBatch")
                        row("fElementPlace") = Elementrow("fElementPlace")
                        row("fElementStatus") = Elementrow("fElementStatus")
                        ElmentTable.Rows.Add(row)
                    Next
                    ElmentTable.AcceptChanges()
                    Me.DGVElement.DataSource = ElmentTable
                End If
            End If
        Catch ex As Exception
            MessageBox.Show("Error : BtnLoadElement_Click" + ex.ToString, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    Private Sub TxtPackingDate_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles TxtPackingDate.Click
        Try
            Me.TxtPackingDate.Text = ServerDate
        Catch ex As Exception
            MessageBox.Show("Error : TxtPackingDate_Click" + ex.ToString, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    Private Sub TxtPackingDateQ_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles TxtPackingDateQ.Click
        Try
            Me.TxtPackingDateQ.Text = ServerDate
        Catch ex As Exception
            MessageBox.Show("Error : TxtPackingDateQ_Click" + ex.ToString, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)

        End Try
    End Sub

    Private Sub TxtPackingDateQ_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TxtPackingDateQ.TextChanged

    End Sub

    Private Sub DGVLoadElement_RowPostPaint(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewRowPostPaintEventArgs) Handles DGVLoadElement.RowPostPaint

        Try
            e.Graphics.DrawString(e.RowIndex + 1, Me.DGVLoadElement.DefaultCellStyle.Font, Brushes.Black, e.RowBounds.X + 5, e.RowBounds.Y + 4)

        Catch ex As Exception
            MessageBox.Show("Error : DGVLoadElement_RowPostPaint" + ex.ToString, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)

        End Try
    End Sub

    Private Sub DGVLoadElement_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DGVLoadElement.CellContentClick

    End Sub

    Private Sub DGVMasterQ_RowPostPaint(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewRowPostPaintEventArgs) Handles DGVMasterQ.RowPostPaint
        Try
            e.Graphics.DrawString(e.RowIndex + 1, Me.DGVMasterQ.DefaultCellStyle.Font, Brushes.Black, e.RowBounds.X + 5, e.RowBounds.Y + 4)
        Catch ex As Exception
            MessageBox.Show("Error : DGVMasterQ_RowPostPaint" + ex.ToString, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    Private Sub BtnCopytoDevice_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)

    End Sub

    Private Sub DGVElement_RowPostPaint(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewRowPostPaintEventArgs) Handles DGVElement.RowPostPaint
        e.Graphics.DrawString(e.RowIndex + 1, Me.DGVElement.DefaultCellStyle.Font, Brushes.Black, e.RowBounds.X + 5, e.RowBounds.Y + 4)
    End Sub



#Region " Menu Operation"

    Private Sub SaveTOToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveTOToolStripMenuItem.Click
        Try
            Dim mPackingBillNum As String
            Dim FilePathstr As String = ""
            Dim Sw As StreamWriter
            Dim Sr As StreamReader
            Dim content As String = String.Empty

            If Me.DGVMasterQ.Rows.Count > 0 Then
                If Not Me.DGVMasterQ.CurrentRow Is Nothing Then
                    mPackingBillNum = Me.DGVMasterQ.CurrentRow.Cells("fPackingBillNum").Value
                End If
            Else
                MessageBox.Show("沒有數據可以下載", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
                Exit Sub
            End If
            'With Me.SaveFileDialog1
            '    .FileName = "itemmas.txt"
            '    .Filter = "文本文件(*.txt)|*.txt"
            'End With
            If Me.SaveFileDialog1.ShowDialog = DialogResult.OK Then
                FilePathstr = Me.SaveFileDialog1.FileName
            Else
                Exit Sub
            End If

            Dim Rows() As DataRow = PackingRst.Tables(1).Select("fPackingBillNum='" & mPackingBillNum & "'")

            If File.Exists(FilePathstr) Then
                Sr = New StreamReader(FilePathstr, System.Text.Encoding.Default)
                content = Sr.ReadToEnd
                content = Nothing
                Sr.Close()
                Sw = New StreamWriter(FilePathstr, False, System.Text.Encoding.Default)
                If Rows.Length > 0 Then
                    For Each row As DataRow In Rows
                        Sw.WriteLine(row("felement") & vbTab & row("felement"))
                        Sw.Flush()
                    Next
                    Sw.Close()
                End If
            Else
                Sw = New StreamWriter(FilePathstr, False, System.Text.Encoding.Default)
                If Rows.Length > 0 Then
                    For Each row As DataRow In Rows
                        Sw.WriteLine(row("felement") & vbTab & row("felement"))
                        Sw.Flush()
                    Next
                    Sw.Close()
                End If
            End If
        Catch ex As Exception
            MessageBox.Show("Error : BtnCopytoDevice_Click" + ex.ToString, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExitToolStripMenuItem.Click
        Exit Sub
    End Sub

    Public Function GetDataSetFromCSV(ByVal filePath As String, ByVal fileName As String) As DataTable
        Try
            Dim dt As New DataTable
            Dim strConnection As String = EXCELCONNECTION & "Data Source=" & filePath & ";"
            Dim connection As OleDb.OleDbConnection = New OleDb.OleDbConnection(strConnection)
            connection.Open()
            Dim strCommand As String = "SELECT * FROM " + fileName
            Dim adapter As New OleDb.OleDbDataAdapter(strCommand, connection)
            adapter.Fill(dt)

            Dim NewRow As DataRow = dt.NewRow
            NewRow(0) = dt.Columns(0).ColumnName
            dt.Rows.Add(NewRow)
            dt.AcceptChanges()
            Return dt
        Catch ex As Exception
            MessageBox.Show(ex.Message & "ex.GetDataSetFromCSV")
        End Try
    End Function

    Private Sub BtnFromCASIO_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnFromCASIO.Click

    End Sub

    Private Sub SaveXmlToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveXmlToolStripMenuItem.Click
        Try
            'Dim mPackingBillNum As String
            Dim mPackingBillNum As System.Text.StringBuilder = New System.Text.StringBuilder
            Dim FilePathstr As String = ""
            Dim Sw As StreamWriter
            Dim Sr As StreamReader
            Dim content As String = String.Empty
            Dim Xmlpath As String = ReturnXMLPathDown()
            Dim CasioNum As String = String.Empty
            If Me.DGVMasterQ.Rows.Count > 0 Then
                'If Not Me.DGVMasterQ.CurrentRow Is Nothing Then
                '    mPackingBillNum = Me.DGVMasterQ.CurrentRow.Cells("fPackingBillNum").Value
                'End If
                If Me.DGVMasterQ.SelectedRows.Count > 0 Then
                    For i As Integer = 0 To Me.DGVMasterQ.SelectedRows.Count - 1
                        Dim fPackingBillNum As String = Me.DGVMasterQ.SelectedRows(i).Cells("fPackingBillNum").Value & ""
                        If mPackingBillNum.Length > 0 Then
                            mPackingBillNum.Append(",")
                        End If
                        mPackingBillNum.Append("'")
                        mPackingBillNum.Append(fPackingBillNum)
                        mPackingBillNum.Append("'")
                    Next
                End If
            Else
                MessageBox.Show("沒有數據可以下載", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
                Exit Sub
            End If

            'With Me.SaveFileDialog1
            '    .FileName = "Packing.xml"
            '    .Filter = "Xml文件(*.xml)|*.xml"
            'End With
            'If Me.SaveFileDialog1.ShowDialog = DialogResult.OK Then
            '    FilePathstr = Me.SaveFileDialog1.FileName
            'Else
            '    Exit Sub
            'End If

            Dim Rows() As DataRow = PackingRst.Tables(1).Select("fPackingBillNum in (" & mPackingBillNum.ToString & ")")

            '構造表
            Dim mTable As DataTable = New DataTable("packing")
            With mTable.Columns
                '.Add("fPackingBillNum")
                .Add("fBoxNum")
                '.Add("fBoNum")
                '.Add("fBarcode")
                .Add("fEnname")
                '.Add("fSupplierItem")
                .Add("fElement")
                '.Add("fElementAmount")
                '.Add("fElementUnit")
                '.Add("fElementBatch")
                '.Add("fElementPlace")
                '.Add("fElementStatus")
            End With
            Dim Frm_SelectCasioNo As Frm_SelectCasioNo = New Frm_SelectCasioNo
            Frm_SelectCasioNo.ShowDialog()
            If Frm_SelectCasioNo.BtnYes.DialogResult <> DialogResult.OK Then
                Exit Sub
            End If
            CasioNum = Frm_SelectCasioNo.CBCasioNO.Text
            If Xmlpath.Length = 0 Then
                MessageBox.Show("沒有設置下載路徑", "路徑設置", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                Exit Sub
            End If
            If CasioNum.Length = 0 Then
                MessageBox.Show("請選擇Casio編號", " 提示", MessageBoxButtons.OK, MessageBoxIcon.Information)
                Exit Sub
            End If

            Xmlpath = Xmlpath + "Packing-" + Frm_SelectCasioNo.CBCasioNO.Text.ToString.Trim + ".XML"
            'mTable.WriteXml(Xmlpath, System.Data.XmlWriteMode.WriteSchema, True)

            If File.Exists(Xmlpath) Then
                File.Delete(Xmlpath)
                If Rows.Length > 0 Then
                    For Each row As DataRow In Rows
                        mTable.ImportRow(row)
                    Next
                    mTable.AcceptChanges()
                    mTable.WriteXml(Xmlpath, System.Data.XmlWriteMode.WriteSchema, True)
                End If

            Else
                If Rows.Length > 0 Then
                    For Each row As DataRow In Rows
                        mTable.ImportRow(row)
                    Next
                    mTable.AcceptChanges()
                    mTable.WriteXml(Xmlpath, System.Data.XmlWriteMode.WriteSchema, True)
                End If

            End If
            MessageBox.Show("保存成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information)

        Catch ex As Exception
            MessageBox.Show("Error : BtnCopytoDevice_Click" + ex.ToString, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try

    End Sub

#End Region

    Private Sub TxtBoxNum_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TxtBoxNum.TextChanged

    End Sub
End Class
